package com.applet.common.config;

import com.applet.common.utils.MailProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Properties;

@Component
@Configuration
public class MailConfig {

    @Resource
    private MailProperties mailProperties;

    public String getFrom() {
        return mailProperties.getFrom();
    }

    public JavaMailSender getMailSender(String username, String password) {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(mailProperties.getHost());
        mailSender.setPort(mailProperties.getPort());
        // 如果没有自定义的用户，就使用配置类里面的用户
        mailSender.setUsername(StringUtils.defaultIfBlank(username, mailProperties.getUsername()));
        mailSender.setPassword(StringUtils.defaultIfBlank(password, mailProperties.getPassword()));
//        StringUtils.blankToDefaul()
        Properties props = mailSender.getJavaMailProperties();
        // starttls.enable = true 时为 smtps
        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtp.auth", mailProperties.getAuth());
        props.put("mail.smtp.starttls.enable", mailProperties.getStarttlsEnable());
        props.put("mail.smtp.ssl.trust", mailProperties.getSslTrust());
        props.put("mail.debug", "true");

        return mailSender;
    }
}
